/**
 * Copyright @ 2019 HoldTime Inner Mongolia Co. Ltd.
 */
package com.holdtime.jtt809dataservice.server.util;

import com.holdtime.jtt809dataservice.server.socket.TcpClient;
import io.netty.channel.ChannelHandlerContext;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 项目名称： jtt809gateway<br>
 * 功能描述： LinksManager概述：主从链路管理器<br>
 * 创  建 人： guoai<br>
 * 创建日期： 2019年7月27日<br>
 * 修  改 人：  <br>
 * 修改时间：<br>
 * 修改内容：<br>
 * 版      本： 1.0.0
 */
public class LinksManager {

    private static final ConcurrentHashMap<Object, ChannelHandlerContext> mainLinksSession = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Object, TcpClient> subLinksClient = new ConcurrentHashMap<>();

    private LinksManager() {
    }

    /**
     * 存入主链路session
     * @param number
     * @param channelHandlerContext
     */
    public static void putMainLink(Object number, ChannelHandlerContext channelHandlerContext) {
        ChannelHandlerContext oldChannelHandlerContext = mainLinksSession.get(number);
        if (oldChannelHandlerContext != null && oldChannelHandlerContext != channelHandlerContext) {
            oldChannelHandlerContext.close();
            oldChannelHandlerContext = null;
        }
        mainLinksSession.put(number, channelHandlerContext);
    }

    /**
     * 存入从链路tcpClient
     * @param number
     * @param tcpClient
     */
    public static void putSubLink(Object number, TcpClient tcpClient) {
        TcpClient oldClient = subLinksClient.get(number);
        if (oldClient != null && oldClient != tcpClient) {
            oldClient.dispose();
            oldClient = null;
        }
        subLinksClient.put(number, tcpClient);
    }

    /**
     * 获取主链路session
     * @param number
     * @return
     */
    public static ChannelHandlerContext getMainLink(Object number) {
        return mainLinksSession.get(number);
    }

    /**
     * 获取从链路tcpClient
     * @param number
     * @return
     */
    public static TcpClient getSubLink(Object number) {
        return subLinksClient.get(number);
    }

    /**
     * 移除主链路session
     * @param number
     */
    public static void removeMainLink(Object number) {
        ChannelHandlerContext oldChannelHandlerContext = mainLinksSession.get(number);
        if (oldChannelHandlerContext != null) {
            oldChannelHandlerContext.close();
            oldChannelHandlerContext = null;
        }
        mainLinksSession.remove(number);
    }

    /**
     * 移除从链路tcpClient
     * @param number
     */
    public static void removeSubLink(Object number) {
        TcpClient oldClient = subLinksClient.get(number);
        if (oldClient != null) {
            oldClient.dispose();
            oldClient = null;
        }
        subLinksClient.remove(number);
    }
}
